package com.lemon.admin.controller;

import com.lemon.admin.bean.Account;
import com.lemon.admin.bean.User;
import com.lemon.admin.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
@Slf4j
@Controller
public class IndexController {
    @Autowired
    AccountService accountService;
    @GetMapping(value={"/","/login"})
    public String loginPage(){
        return "login";
    }
    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){

        if(StringUtils.hasLength(user.getName()) && "123456".equals(user.getPwd())){
            //把登陆成功的用户保存起来
            session.setAttribute("loginUser",user);
            //登录成功重定向到main.html;  重定向防止表单重复提交
            return "redirect:/index.html";
        }else {
            model.addAttribute("msg","账号密码错误");
            //回到登录页面
            return "login";
        }

    }
    @GetMapping("/index.html")
    public String mainPage(HttpSession session,Model model){
        log.info("当前的方法是：{}","mainPage");
//        Object loginUser = session.getAttribute("loginUser");
//        if(loginUser!=null){
//            return "index";
//        }
//        else {
//            model.addAttribute("msg","请重新登录");
//            return "login";
//        }
        return "index";
    }
    @ResponseBody
    @GetMapping("/acc")
    public Account getByHost(@RequestParam("host") String host){
        return accountService.getbyHost(host);
    }
}
